﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace OpticalPowerMeter
{
    /// <summary>
    /// ProductEditWindow.xaml 的交互逻辑
    /// </summary>
    public partial class ProductEditWindow : Window
    {
        public ProductEditWindow()
        {
            InitializeComponent();
            InitProductList(); //从本地配置文件获取机型清单，显示在列表中
            InitWavelengthList(); //初始化可选波长列表
        }

        #region 绑定显示的属性
        //机型清单表头字号
        static DependencyProperty DataGridHeadFontProperty = DependencyProperty.Register(
            "DataGridHeadFont",
            typeof(double),
            typeof(ProductEditWindow)
            );

        //单元字号
        static DependencyProperty CellFontProperty = DependencyProperty.Register(
            "CellFont",
            typeof(double),
            typeof(ProductEditWindow)
            );

        //单元高度
        static DependencyProperty CellHeightProperty = DependencyProperty.Register(
            "CellHeight",
            typeof(double),
            typeof(ProductEditWindow)
            );

        //数据列宽
        static DependencyProperty DataGridColumnWidthProperty = DependencyProperty.Register(
            "DataGridColumnWidth",
            typeof(double),
            typeof(ProductEditWindow)
            );

        //设备名称字号，包括Label和文本框内的字号
        static DependencyProperty ProductNameFontSizeProperty = DependencyProperty.Register(
            "ProductNameFontSize",
            typeof(double),
            typeof(ProductEditWindow)
            );

        //机型输入框高度
        static DependencyProperty ProductNameBoxHeightProperty = DependencyProperty.Register(
            "ProductNameBoxHeight",
            typeof(double),
            typeof(ProductEditWindow)
            );

        //机型输入框宽度
        static DependencyProperty ProductNameBoxWidthProperty = DependencyProperty.Register(
            "ProductNameBoxWidth",
            typeof(double),
            typeof(ProductEditWindow)
            );

        //机型输入框边距
        static DependencyProperty ProductNameBoxMarginProperty = DependencyProperty.Register(
            "ProductNameBoxMargin",
            typeof(Thickness),
            typeof(ProductEditWindow)
            );

        //Save按钮边距
        static DependencyProperty SaveButtonMarginProperty = DependencyProperty.Register(
            "SaveButtonMargin",
            typeof(Thickness),
            typeof(ProductEditWindow)
            );

        //Delete按钮边距
        static DependencyProperty DeleteButtonMarginProperty = DependencyProperty.Register(
            "DeleteButtonMargin",
            typeof(Thickness),
            typeof(ProductEditWindow)
            );
        #endregion

        //初始化可选波长列表（这部分值放置控件，排版及大小变化在Size_Changed中调整）
        private void InitWavelengthList()
        {
            List<MyWavelength> myWavelengths = WavelengthListManagement.GetInstance().GetWavelengthList();
            for(int i = 0; i < myWavelengths.Count; i++)
            {
                CheckBox checkBox = new CheckBox();
                checkBox.Content = myWavelengths[i].Wavelength;
                checkBox.HorizontalAlignment = HorizontalAlignment.Left;
                checkBox.VerticalAlignment = VerticalAlignment.Top;
                WavelengthGrid.Children.Add(checkBox);
                checkBox.Checked += new RoutedEventHandler(WavelengthChecked);
                checkBox.Unchecked += new RoutedEventHandler(WavlengthUnchecked);
            }
        }

        //复选按钮选中时显示绿色
        private void WavelengthChecked(object sender,RoutedEventArgs args)
        {
            CheckBox checkBox = sender as CheckBox;
            checkBox.Foreground = Brushes.Green;
        }

        //复选按钮未选中时显示黑色
        private void WavlengthUnchecked(object sender,RoutedEventArgs args) {
            CheckBox checkBox = sender as CheckBox;
            checkBox.Foreground = Brushes.Black;
        }

        //选中机型时，将它的机型名称、波长列表、线性点显示在右侧
        private void ProductNameDataGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
        {
            int index = ProductNameDataGrid.SelectedIndex;
            if (index < 0)
            {
                return;
            }
            List<string> productnameList = ProductManagement.GetInstance().GetProductList();
            string productname = productnameList[index];
            List<string> wavlengthList = ProductManagement.GetInstance().GetWaveList(productname);
            //显示机型
            ProductNameTextBox.Text = productname;
            //显示波长列表
            foreach (object control in WavelengthGrid.Children)
            {
                if (!control.GetType().Name.EndsWith("CheckBox")) {
                    continue;
                }
                CheckBox check = control as CheckBox;
                if (wavlengthList.Contains(check.Content.ToString()))
                {
                    check.IsChecked = true;
                }
                else
                {
                    check.IsChecked = false;
                }
            }
        }


        //尺寸发生变化时，调整控件尺寸
        private void Size_Changed(object sender,SizeChangedEventArgs args) {
            #region 刷新左侧机型列表字号等内容
            Grid parentGrid = (Grid)ProductNameDataGrid.Parent;
            double parentWidth = parentGrid.ActualWidth;
            ProductNameDataGrid.Width = parentWidth;
            double dataGridWidth = parentWidth;
            SetValue(DataGridColumnWidthProperty, dataGridWidth);  //设置列宽
            double height = dataGridWidth / 5; //宽度与高度比5:1
            double headFontSize = Math.Round((height - 10) / 1.27,1);  //head字号
            SetValue(DataGridHeadFontProperty,headFontSize);
            SetValue(CellFontProperty,headFontSize-2); //内容比head小2个字号
            SetValue(CellHeightProperty, Math.Round((headFontSize - 2)*1.27,1));
            #endregion
            #region 刷新机型名称部分字号及边距等
            double productNameGridWidth = ProductNameGrid.ActualWidth;
            //double productNameGridHeight = ProductNameGrid.ActualHeight;
            double productNameFontSize = Math.Round((productNameGridWidth * 0.3 - 10) / 4 , 1);  //机型名称占总宽度30%
            SetValue(ProductNameFontSizeProperty, productNameFontSize);
            double productNameBoxWidth = Math.Round(productNameGridWidth * 0.7 - 20 , 1);
            double productNameBoxHeight = Math.Round(productNameFontSize * 1.27);
            SetValue(ProductNameBoxHeightProperty, productNameBoxHeight); //机型输入框的尺寸
            SetValue(ProductNameBoxWidthProperty, productNameBoxWidth);
            double boxLeft = Math.Round(productNameGridWidth * 0.3 + 10,1);
            SetValue(ProductNameBoxMarginProperty,new Thickness(boxLeft,0,0,0));
            #endregion
            #region 刷新按钮部分边距
            double saveButtonLeft = Math.Round(productNameGridWidth / 5,1);
            SetValue(SaveButtonMarginProperty, new Thickness(saveButtonLeft, 0, 0, 0));
            double deleteButtonLeft = Math.Round(productNameGridWidth / 5 * 3,1);
            SetValue(DeleteButtonMarginProperty,new Thickness(deleteButtonLeft,0,0,0));
            #endregion
            #region 调整波长列表字号及位置
            double wavelengthCheckBoxFontSize = headFontSize - 2;
            UIElementCollection waveElementCollection = WavelengthGrid.Children; //获取控件清单
            //遍历复选按钮设置字号
            foreach (UIElement element in waveElementCollection) {
                if (element.GetType().Name.EndsWith("CheckBox")) {
                    CheckBox check = element as CheckBox;
                    check.FontSize = wavelengthCheckBoxFontSize;
                }
            }
            System.Threading.Thread thread = new System.Threading.Thread(ChangeMargin);
            thread.Start();
            #endregion
        }

        //刷新波长选择框的位置
        private void ChangeMargin() {
            App.Current.Dispatcher.Invoke(new Action(()=> {
                UIElementCollection waveElementCollection = WavelengthGrid.Children; //获取控件清单
                List<CheckBox> checkBoxList = new List<CheckBox>();
                foreach (UIElement element in waveElementCollection)
                {
                    if (element.GetType().Name.EndsWith("CheckBox"))
                    {
                        CheckBox check = element as CheckBox;
                        checkBoxList.Add(check);
                    }
                }
                double wavelengthCheckBoxFontSize = checkBoxList[0].FontSize;
                double wavelengthParentWidth = WavelengthGrid.ActualWidth; //父框架宽度
                double boxWidth = wavelengthCheckBoxFontSize * 2.35 + 20; //控件宽度
                double boxHeight = ((CheckBox)waveElementCollection[0]).ActualHeight; //控件高度
                int countOfEveryRow = (int)(wavelengthParentWidth / boxWidth);  //计算一行可以放几个控件
                double spaceWidth = wavelengthParentWidth - boxWidth * countOfEveryRow; //放置完控件以后剩余的空白部分
                double leftMargin= spaceWidth / (countOfEveryRow + 1); //与左边控件的左边距
                for (int i = 0; i < checkBoxList.Count; i++)
                {
                    int row = i / countOfEveryRow;
                    int column = i % countOfEveryRow;
                    checkBoxList[i].Margin = new Thickness(column * boxWidth + (column + 1) * leftMargin, row * boxHeight, 0, 0);
                }
            }));
        }

        //读取机型清单，显示在列表中
        private void InitProductList()
        {
            List<string> productList = ProductManagement.GetInstance().GetProductList();
            ProductNameDataGrid.ItemsSource = null;
            ProductNameDataGrid.ItemsSource = productList;
        }

        //保存按钮点击时
        private void SaveButton_Click(object sender, RoutedEventArgs args) {
            string productname = ProductNameTextBox.Text.Trim();
            if (productname == "")
            {
                MessageBox.Show("产品型号为空", "无法添加空型号", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }
            #region 获取选中的波长列表，放入一个List
            List<string> wavelengthList = new List<string>();
            foreach (object control in WavelengthGrid.Children)
            {
                if (control.GetType().Name.EndsWith("CheckBox"))
                {
                    CheckBox check = control as CheckBox;
                    if ((bool)check.IsChecked)
                    {
                        wavelengthList.Add(check.Content.ToString());
                    }
                }
            }
            #endregion
            Product p = new Product();
            p.ProductName = productname;
            p.Wavelengthes = wavelengthList;
            ProductManagement.GetInstance().SaveData(p);
            MessageBox.Show("保存机型" + productname + "完成", "保存完成", MessageBoxButton.OK, MessageBoxImage.Information);
            //刷新列表
            InitProductList();
        }

        //删除按钮点击时
        private void DeleteButton_Click(object sender,RoutedEventArgs args) {
            string productname = ProductNameTextBox.Text.Trim();
            if (productname == "")
            {
                return;
            }
            MessageBoxResult clickButton = MessageBox.Show("是否确定要删除" + productname, "删除机型", MessageBoxButton.YesNo, MessageBoxImage.Question);
            if (clickButton == MessageBoxResult.Yes)
            {
                ProductManagement.GetInstance().DeleteProduct(productname);
            }
            //刷新列表
            InitProductList();
        }

    }
}
